﻿using NhWeather.Modbus;
using NhWeather.nModbusDevice;
using NhWeather.Properties;
using NhWeather.Register;
using NhWeather.Service;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;

namespace NhWeather.nModbusDevice;

/// <summary>
/// PageDevcie.xaml 的交互逻辑
/// </summary>
public partial class ControlDevcie : UserControl, INotifyPropertyChanged
{
    private readonly DataRecorder _dataRecorder;

    public ControlDevcie(byte address = 8)
    {
        InitializeComponent();
        _dataRecorder = new(address);
        DataContext = _dataRecorder;
        CommunicationService.Instance.DataRecorders.Add(_dataRecorder);
        DgView.ItemsSource = _dataRecorder.Registers;
    }

    /// <summary>
    /// 按常规记录仪初始化寄存器
    /// </summary>
    /// <param name="isRecorder">为记录仪时，前3个寄存器为时间</param>
    public void InitializeRegisters(bool isRecorder)
    {
        _dataRecorder.InitializeRegisters(isRecorder);
    }

    private void CheckBox模拟记录仪_Checked(object sender, RoutedEventArgs e)
    {
        if (DgView == null) return; // 窗口未加载完成

        // 初始化数据记录仪并更新数据源
        InitializeDataRecorder(true);
        ((CheckBox)sender).Content = "模拟记录仪";
    }

    private void CheckBox模拟记录仪_Unchecked(object sender, RoutedEventArgs e)
    {
        // 初始化数据记录仪并更新数据源
        InitializeDataRecorder(false);
        ((CheckBox)sender).Content = "模拟传感器";
    }

    /// <summary>
    /// 初始化数据记录仪
    /// </summary>
    /// <param name="isJly">true头3个寄存器为时间，flase都是寄存器</param>
    private void InitializeDataRecorder(bool isJly)
    {
        _dataRecorder.UpdataTimeRegisters(isJly);
    }

    /// <summary>
    /// 加新行增加寄存器
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void DgView_AddingNewItem(object sender, AddingNewItemEventArgs e)
    {
        // 创建一个新的寄存器对象
        var newRegister = new SensorRegister(2000, 0)
        {
            RegAddress = (ushort)_dataRecorder.Registers.Count
        };

        // 设置新项
        e.NewItem = newRegister;
    }

    private void CloseButton_Click(object sender, RoutedEventArgs e)
    {
        // 从父容器中移除当前控件
        if (this.Parent is Panel parent)
        {
            parent.Children.Remove(this);
        }

        // 从 CommunicationService 中移除对应的 DataRecorder
        CommunicationService.Instance.DataRecorders.Remove(_dataRecorder);
    }
    private void TextBlock_TextInput(object sender, TextChangedEventArgs e)
    {
        if (sender is TextBox textBox)
        {
            if (int.TryParse(textBox.Text, out int value))
            {
                if (value > short.MaxValue)
                {
                    textBox.Text = short.MaxValue.ToString();
                }
                else if (value < short.MinValue)
                {
                    textBox.Text = short.MinValue.ToString();
                }
            }
        }
    }

    #region 属性通知
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }


    /// <summary>
    /// 更新属性并触发属性更改通知
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="properValue"></param>
    /// <param name="newValue"></param>
    /// <param name="onChanged">如要更改属性要运行的方法</param>
    /// <param name="propertyName"></param>
    protected void UpdateProperty<T>(ref T properValue, T newValue, Action onChanged = null, [CallerMemberName] string propertyName = null)
    {
        if (Equals(properValue, newValue))
        {
            return;
        }
        properValue = newValue;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
    }
    #endregion

    private void TextBlock_TextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {

    }
}

